package
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.ColorTransform;
	import flash.geom.Matrix;
	
	public class MotionReactor_AccColor
	{
		//VARIABLES INTERNAS SETEABLES OBLIGATORIAS.
		
		public var clip:Sprite;	
		public var listener:Object;
		
		//VARIABLES INTERNAS SETEABLES OPCIONALES.
			
			var rFactor:Number = 1;
			var gFactor:Number = 0;
			var bFactor:Number = 0;
			var accFactor:Number = 0.1;
			var frictionFactor:Number = 0.9;
			
		//VARIABLES INTERNAS.
		
			var subClip:Sprite;
			var newSub:Sprite;
			var fX:Number = 0;
			var fY:Number = 0;
		
		//CONSTRUCTOR.
		public function MotionReactor_AccColor()
		{
			
		}
		
		//INIT.
		public function init():void
		{
			//IDENTIFICA EL SUBCLIP Y LO ESCONDE.
			subClip = Sprite(clip.getChildAt(0));
			subClip.visible = false;
			
			//INICIALIZA EL REDIBUJADOR.
			newSub = new Sprite();
			clip.addChild(newSub);
			newSub.x = -subClip.width/2;
			newSub.y = -subClip.height / 2;
			
			//INICIA EL ENTERFRAME.
			clip.addEventListener(Event.ENTER_FRAME, enterFrameHandler);
		}
		
		//ENTERFRAME.
		private function enterFrameHandler(evt:Event):void
		{
			//CALCULA LOS VALORES QUE POR MEDIO DE LA ACELERACION AFECTAN EL COLOR.
				
				//OBTIENE LOS FACTORES DE COLOR A PARTIR DE LAS ACELERACION CONTENIDAS.
				var aX:Number = Math.abs(listener.aX);
				var aY:Number = Math.abs(listener.aY);
				aX = aX > 0.01 ? aX : 0;
				aY = aY > 0.01 ? aY : 0;
				var afX:Number = aX*accFactor;
				var afY:Number = aY*accFactor;
				
				//APLICA LA ACELERACION PARA AFECTAR LOS FACTORES DE COLOR.
				fX = fX + afX < 1 ? fX + afX : 1;
				fY = fY + afY < 1 ? fY + afY : 1;
			
				//FRICCION DE COLOR.
				fX *= frictionFactor;
				fY *= frictionFactor;
				
				//CALCULA EL VALOR TOTAL.
				var cf:Number = (fX + fY)/2
				
			//REDIBUJA EL SUBCLIP.
			var bmpData:BitmapData = new BitmapData(subClip.width, subClip.height, true, 0x00000000);
			var cTransform:ColorTransform = new ColorTransform(1, 1, 1, 1, 255*cf*rFactor, 255*cf*gFactor, 255*cf*bFactor, 0);
			var matrix:Matrix = new Matrix();
			matrix.translate(subClip.width/2, subClip.height/2);
			bmpData.draw(subClip, matrix, cTransform);
			var bmp:Bitmap = new Bitmap(bmpData);
			newSub.addChild(bmp);
		}
	}
}